package com.yoyo.itravel.web.filter;

import com.yoyo.itravel.bean.User;
import com.yoyo.itravel.constants.UserConstant;
import com.yoyo.itravel.exceptions.UserException;
import com.yoyo.itravel.service.IUserService;
import com.yoyo.itravel.service.impl.UserServiceImpl;
import com.yoyo.itravel.utils.MD5Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 用户自动登录过滤器
 * @Author HZX
 * @Version 1.0
 * @Date 2020/6/20 11:24
 */
@WebFilter("/*")
public class AutoLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Object obj = request.getSession().getAttribute(UserConstant.USER);

        // 如果从session中获取user为空，我们才需要获取cookie进行登陆以及存放到session中,否则直接放行
        if (obj == null) {
            // 获取cookies
            Cookie[] cookies = request.getCookies();
            Cookie cookie = null;
            // 先要判断获取的cookies是否存在
            if (cookies != null && cookies.length > 0) {
                // 遍历cookies
                for (Cookie c : cookies) {
                    String name = c.getName();
                    if ((UserConstant.AUTO_LOGIN_INFO).equals(name)) {
                        // 说明cookie中存在自动登录信息
                        cookie = c;
                        break;
                    }
                }
            }

            try {
                if (cookie != null) { // 说明存在自动登陆的cookie
                    // 我们需要把cookie的值读取出来存放到session中
                    String[] split = cookie.getValue().split("&");
                    // 调用service层登陆
                    IUserService service = new UserServiceImpl();

                    // 进行登录操作
                    User user = service.login(split[0], MD5Utils.md5(split[1]));
                    // 判断是否登录成功
                    if (user != null) { // 说明登陆成功
                        request.getSession().setAttribute(UserConstant.USER, user);
                        // 跳转首页
//                        response.sendRedirect(request.getContextPath() + "/index.jsp");
                    }
                }
            } catch (UserException e) {
                e.printStackTrace();
            }
        }

        // 如果不存在直接 放行
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

